package p11hightBright;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import javax.print.Doc;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 高亮
 */
public class IndexUitls11 {
    public void index() {
        IndexWriter indexWriter = null;
        try {
            File file = new File("d:/lucene/test.docx");
            Directory directory = FSDirectory.open(new File("d:/lucene/index2"));
            IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35));
            indexWriter = new IndexWriter(directory, config);
            Document document = new Document();
            //document.add(new Field("content", new FileReader(file)));

            //使用tika 解析文件
            document.add(new Field("content", new Tika().parse(file)));
            indexWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   public IndexSearcher getSearch() throws IOException {
       Directory directory = FSDirectory.open(new File("d://lucene/index02"));
       IndexReader indexReader = IndexReader.open(directory);
       IndexSearcher indexSearcher = new IndexSearcher(indexReader);
       return indexSearcher;
   }

    /**
     * 单个测试高亮
     * @throws IOException
     * @throws InvalidTokenOffsetsException
     */
    public void hightBright() throws IOException, InvalidTokenOffsetsException {
        String txt="this is china ,i love china";
        TermQuery query=new TermQuery(new Term("content","china"));
        QueryScorer queryScorer=new QueryScorer(query);
        Fragmenter fragmenter=new SimpleSpanFragmenter(queryScorer);
        //默认标签事<B>,这里可以设置标签
        Formatter formatter=new SimpleHTMLFormatter("<span>","</span>");
        Highlighter highlighter=new Highlighter(queryScorer);
        highlighter.setTextFragmenter(fragmenter);
        String str=highlighter.getBestFragment(new StandardAnalyzer(Version.LUCENE_35),"content",txt);
        System.out.println(str);

    }


    /**
     * 此方法 未实现完
     *
     * 比如一个网页的内容，我们如果做高亮的话，就要存储，但要存储的话就太大了，但
     * 我们可以存储这个文件的路径，然后，再读取内容
     */

    public void searchByHightLight() throws IOException, ParseException, InvalidTokenOffsetsException {
        IndexSearcher indexSearcher=getSearch();
        Analyzer analyzer= new StandardAnalyzer(Version.LUCENE_35);
        //QueryParser parser=new QueryParser(Version.LUCENE_35,"content",analyzer);
        //这个parser 可以一下搜两个字段，（getHighLight 高亮部分有个queryScore）
        MultiFieldQueryParser parser=new MultiFieldQueryParser(Version.LUCENE_35,new String[]{"title","content"},analyzer);
        Query query=parser.parse("china");
        TopDocs topDocs=indexSearcher.search(query,20);
        ScoreDoc [] scoreDocs=topDocs.scoreDocs;
        for(ScoreDoc sd:scoreDocs){
            Document document=indexSearcher.doc(sd.doc);
            //1,比如我们这里想对content 种包含 “china”的部分进行高亮，，由于文件内容太多，
            //我们没有进行存储，我们在索引的时候，可以存下路径，然后再读内容，
            //这里我们先假定存了内容
            String content=document.get("content");
            //2,进行高亮
            content=getHighLight(query,analyzer,"content",content);

        }
        indexSearcher.close();
    }

    public String getHighLight(Query query, Analyzer analyzer,String fieldName,String txt) throws IOException, InvalidTokenOffsetsException {
        //1，查询
        QueryScorer queryScorer=new QueryScorer(query);
        //2 分割
        Fragmenter fragmenter=new SimpleSpanFragmenter(queryScorer);
        //3 设置标签
        //默认标签事<B>,这里可以设置标签
        Formatter formatter=new SimpleHTMLFormatter("<span>","</span>");
        //4，高亮
        Highlighter highlighter=new Highlighter(queryScorer);
        highlighter.setTextFragmenter(fragmenter);
        String str=highlighter.getBestFragment(analyzer,fieldName,txt);
        return  str;
    }

}
